package com.example.user.service;

import com.example.commons.config.SimpleGrantedAuthorityWrapper;
import com.example.commons.entity.Users;
import com.example.commons.exception.BusinessException;
import com.example.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService implements UserDetailsService {

    private static final String ROLE_PRE_FIX = "ROLE_";

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = userMapper.selectUserByUserName(username);
        if (null == users) {
            throw new BusinessException("账号/密码密码有误");
        }
        List<SimpleGrantedAuthorityWrapper> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthorityWrapper(ROLE_PRE_FIX + "admin"));
        list.add(new SimpleGrantedAuthorityWrapper("qry"));
        list.add(new SimpleGrantedAuthorityWrapper("upd"));
        list.add(new SimpleGrantedAuthorityWrapper("add"));
        list.add(new SimpleGrantedAuthorityWrapper("del"));

        users.setAuthorities(list);
        return users;
    }
}
